//克隆表单
function cloneForm() {
    //获取父控件
    let divParent = document.getElementById("form_edu").parentNode;
    //克隆表单（一切属性和值）
    let cloneForm = document.getElementById("form_edu").cloneNode(true);
    //更改ID
    cloneForm.id = "form_edu_clone";
    //添加克隆表单
    divParent.appendChild(cloneForm);
}

/*删除表单*/
function removeForm() {
    //获取父控件
    let divParent = document.getElementById("form_edu").parentNode;
    let childLength = $("#formContent").children("form").length
    if (childLength > 2) {
        divParent.removeChild(divParent.lastChild);
    }
}

// 动态生成表格  
function createTable(data) {  
    const table = document.createElement('table');  
    const thead = document.createElement('thead');  
    const tbody = document.createElement('tbody');  

    table.classList.add('table');
  
    // 创建表头  
    const headerRow = document.createElement('tr');  
    data[0].forEach(header => {  
        const th = document.createElement('th');  
        th.textContent = header;  
        headerRow.appendChild(th);  
    });  
    thead.appendChild(headerRow);  
    table.appendChild(thead);  
  
    // 创建表格内容  
    for (let i = 1; i < data.length; i++) {  
        const row = document.createElement('tr');  
        data[i].forEach(cell => {  
            const td = document.createElement('td');  
            td.textContent = cell;  
            row.appendChild(td);  
        });  
        tbody.appendChild(row);  
    }  
    table.appendChild(tbody);  
  
    return table;  
}  

function packData(keys, dicts) {
    let vs = [];
    for (let i = 0; i < dicts.length; i++) {
        const element = dicts[i];
        let item = [];
        for (let j = 0; j < keys.length; j++) {
            let v = element[keys[j]]
            item.push(v ? v : "");
        }
        vs.push(item);
    }
    return [keys].concat(vs);
}

// 将表格插入到指定节点  
function insertTable(table, containerId) {  
    const container = document.getElementById(containerId);  
    if (container.lastChild) {
        container.removeChild(container.lastChild);
    }
    container.appendChild(table);  
}  


//测试API接口
function testApi() {
    //账号
    // let account = $("#account").val();
    // //请求地址
    // let requestUrl = $("#request-url").val();
    //获取参数
    let parameter = getParameter();

    // 调用函数  
    const generatedTable = createTable(packData(parameter[0], parameter[1]));  
    insertTable(generatedTable, 'table-container');

    console.log(parameter[1]);


    // showLoading(true);
    // //访问接口
    // $.ajax({
    //     url: "/api/test/go",
    //     type: "post",
    //     contentType: 'application/json;charset=utf-8',
    //     dataType: 'json',
    //     data: JSON.stringify({
    //         account: account,
    //         requestUrl: requestUrl,
    //         parameter: parameter
    //     }),
    //     success: function (data) {
    //         showLoading(false);
    //         $("#result").html(syntaxHighlight(data));
    //     },
    //     error: function () {
    //         showLoading(false);
    //         alert("请求失败！")
    //     }
    // });
}

/*展示loading*/
function showLoading(show) {
    if (show) {
        $('.container').hide();
        $('.loading').show();
    } else {
        $('.container').show();
        $('.loading').hide();
    }
}

/*获取参数*/
function getParameter() {
    let keyArray = new Array();
    let valueArray = new Array();
    let indexK = 0, indexV = 0;
    let keys = [];
    // $("#formContent input[type=text]").each(function () {
    $("#formContent textarea").each(function () {
        if (this.name == "key") {
            keyArray[indexK] = this.value;
            indexK++;
        } else if (this.name == "textarea") {
            let strList = this.value.split("\n");
            let dict = {};
            for (let i = 0; i < strList.length; i++) {
                let item = strList[i]; 
                let m = item.split(":");
                if (m.length < 2) {
                    m = item.split("：");
                }
                if (m.length < 2) {
                    continue
                }
                let k = m[0].replace(" ", "");
                let v = m[1].match(`[0-9\.]+`)[0];
                if (k == "日期") {
                    v = m[1];
                }
                if (v) {
                    dict[k] = v;
                    if (!keys.includes(k)) {
                        keys.push(k);
                    }
                }
            }
            valueArray[indexV] = dict;
            indexV++;
        }
    })

    return [keys, valueArray];

    // let map = {};
    // for (let i = 0; i < keyArray.length; i++) {
    //     map[keyArray[i]] = valueArray[i];
    // }
    // return map;
}

/*格式化json*/
function syntaxHighlight(json) {
    // json = JSON.parse(json);
    if (typeof json != 'string') {
        json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        let cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

/*修改开发环境*/
function changeServerEnv() {
    let vs = $('select option:selected').val();
    let url = 'https://app-test2.pokio.com/'
    switch (vs) {
        case "1":
            url = 'https://app-test2.pokio.com/'
            break
        case "2":
            url = 'http://192.168.101.180:8109/'
            break
        case "3":
            url = 'https://app.pokio.com/'
            break
    }
    $("#request-url").val(url);
}